"""
@Author：WangYuXiang
@E-mile：Hill@3io.cc
@CreateTime：2021/4/16 15:28
@DependencyLibrary：无
@MainFunction：无
@FileDoc： 
    user.py
    文件说明
@ChangeHistory:
    datetime action why
    example:
    2021/4/16 15:28 change 'Fix bug'
        
"""
from common.auth.models import UserModel
from common.auth.serializers import UserModelSerializer, UserSearchSerializer
from common.utils.authentication import GeneralTokenAuthenticate
from common.utils.site_views import AdminSiteView
from sanic_rest_framework.filters import ORMOrFilter
from sanic_rest_framework.mixins import ListModelMixin
from sanic_rest_framework.status import HttpStatus, RuleStatus
from sanic_rest_framework.views import ViewSetView


class UserViewSet(AdminSiteView):
    queryset = UserModel
    serializer_class = UserModelSerializer
    search_fields = ('@nickname', '@account', '@phone')
    authentication_classes = (GeneralTokenAuthenticate,)

    async def destroy(self, request, *args, **kwargs):
        instance = await self.get_object()
        if instance.is_super_admin:
            return self.success_json_response(msg='不能直接删除超级管理员，请先撤销其超级管理员权限。', status=RuleStatus.STATUS_0_FAIL)
        await self.perform_destroy(instance)
        return self.success_json_response(http_status=HttpStatus.HTTP_200_OK)


class UserSearchView(ListModelMixin, ViewSetView):
    queryset = UserModel
    serializer_class = UserSearchSerializer
    authentication_classes = (GeneralTokenAuthenticate,)
    filter_class = ORMOrFilter
    search_fields = ('@nickname', '@account', '@phone')

    async def list(self, request, *args, **kwargs):
        queryset = await self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        data = await serializer.data
        return self.success_json_response(data=data)
